//
//  KRGatherController.m
//  cookBook
//
//  Created by kuroken on 16/2/5.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#define MAS_SHORTHAND

#import "KRGatherController.h"
#import <PureLayout.h>
#import <MBProgressHUD.h>
#import "MBProgressHUD+KR.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import "KRHttpRecipeTool.h"
#import "KRConst.h"
#import "KRRecommend.h"
#import "KRGatherResult.h"
#import "KRRecommentCell.h"
#import "KRReadPostController.h"
#import "KRNoNetCell.h"

@interface KRGatherController ()

/** KRGatherResult模型 */
@property (nonatomic, strong) KRGatherResult *result;

/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;

/** 指示器 */
@property (nonatomic, weak) UIActivityIndicatorView *indicator;
/** MBProgressHUD */
@property (nonatomic, weak) MBProgressHUD *hud;
@end

@implementation KRGatherController

- (UIActivityIndicatorView *)indicator
{
    if (!_indicator) {
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [indicator setHidesWhenStopped:YES];
        [self.view addSubview:indicator];

        indicator.centerX = self.view.centerX;
        indicator.centerY = self.view.centerY - 50;
        
        self.indicator = indicator;
    }
    return _indicator;
}

- (MBProgressHUD *)hud
{
    if (!_hud) {
        MBProgressHUD *hud = [MBProgressHUD defaultHUD];
        hud.centerX = self.view.centerX;
        hud.centerY = self.view.centerY - 50;
        [self.view addSubview:hud];
        _hud = hud;
    }
    return _hud;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    
    self.tableView.userInteractionEnabled = NO;
    self.tableView.scrollEnabled = NO;
    
    [self loadData];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.result) {
        // 显示指示器
        [self.hud setHidden:NO];
//        [self.indicator startAnimating];
    }

    self.navigationController.navigationBar.hidden = NO;
}

//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [MBProgressHUD hideHUDForView:self.view animated:NO];
//}


- (void)loadData
{
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRTopicIndex;
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;
        
        if (!self.result) {
            // 下拉刷新控件
            self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
            self.error = NO;
            self.tableView.scrollEnabled = YES;
        }
        
        self.result = [KRGatherResult mj_objectWithKeyValues:json[@"result"]];

//        [self.indicator stopAnimating];
        [self.hud setHidden:YES];

        self.tableView.userInteractionEnabled = YES;
        [self.tableView reloadData];

        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        
        if (!self.result) {
            self.error = YES;
            [self.tableView reloadData];
            [self.hud setHidden:YES];
//            [self.indicator stopAnimating];
            self.tableView.userInteractionEnabled = YES;
        }

        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        KRLog(@"%@, %@", self, error);
    }];

}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isError) return 1; // 请求失败
    return self.result.recommentArray.count ? 1 : 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1; // 请求失败
    return self.result.recommentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"请求超时"];
        return cell;
    }
    
    KRRecommentCell *cell = [KRRecommentCell cellWithTableView:tableView];
    cell.recomment = self.result.recommentArray[indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
//        [self.indicator startAnimating];
        [self.hud setHidden:NO];
        return;
    }

    KRReadPostController *readPostVc = [[KRReadPostController alloc] init];
    readPostVc.topicID = self.result.recommentArray[indexPath.row].topicID;
    [self.navigationController pushViewController:readPostVc animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
